<?php
require_once 'bootstrap.php';
$opts = new Zend_Console_Getopt( array(
	'help|h' => 'help',
	'url=s' => 'Url for grabbing',
	'verbose|v' => 'Verbose mode' ) );
$logger = Zend_Log::factory( array(
	array(
		'writerName' => 'Stream',
		'writerParams' => array( 'stream' => 'advego.log' ),
		'formatterName' => 'Simple' ) ) );
Zend_Registry::set( 'logger', $logger );

function main( $url )
{
	$logger = Zend_Registry::get( 'logger' );

	$checkUrl = filter_var( $url, FILTER_VALIDATE_URL );
	if ( !$checkUrl )
	{
		$message = sprintf( 'Invalid url - %s', $url );
		throw new Exception( $message );
	}
	$parts = parse_url( $url );
	$host = sprintf( '%s://%s', $parts[ 'scheme' ], $parts[ 'host' ] );

	$logger->debug( sprintf( 'Search item links by url %s', $url ) );

	$parseObj = new AdvegoParse( $host );
	$savePath = 'data/' . md5( $url );
	$parseObj->setSavePath( $savePath );
	$linksListPage = $parseObj->getLinksListPageByUrl( $url );

	$filename = Zend_Registry::get( 'config' )->get( 'found_links' );
	if ( file_exists( $filename ) )
	{
		unlink( $filename );
	}
	foreach ( $linksListPage as $linkListPage )
	{
		$linksItem = $parseObj->getLinksItem( $linkListPage );
		file_put_contents( $filename, implode( "\r\n", $linksItem ), FILE_APPEND );
		file_put_contents( $filename, "\r\n", FILE_APPEND );
	}
	$logger->debug( sprintf( 'All links save to file %s', $filename ) );
}

try
{
	$opts->parse();
	if ( $opts->help )
	{
		die( $opts->getUsageMessage() );
	}

	if ( $opts->verbose )
	{
		$writer = new Zend_Log_Writer_Stream( 'php://output' );
		$logger->addWriter( $writer );
	}

	$logger = Zend_Registry::get( 'logger' );
	$logger->debug( 'Start script' );
	$message = sprintf( 'ARGV - %s ', print_r( $argv, true ) );
	$logger->debug( $message );

	$url = $opts->url;
	if ( empty( $opts->url ) )
	{
		$grabFilename = Zend_Registry::get( 'config' )->get( 'grab_links' );
		$url = array_shift( file( $grabFilename ) );

		$message = sprintf( 'Grab filename - %s ', $grabFilename );
	    $logger->debug( $message );
	}

	main( $url );

	$logger->debug( 'End script' );
}
catch ( Zend_Console_Getopt_Exception $e )
{
	echo $e->getUsageMessage();
}
catch ( Exception $e )
{
	echo $e->getMessage();
}